package terra.model.object;

import terra.Config;
import terra.definitions.item.ItemDef;
import terra.managers.DefManager;
import terra.model.object.map.MapObject;
import terra.network.packet.Packet;
import terra.network.packet.server.LightInfo;

public class LightObject extends ItemObject {

	boolean onGround = true;
	boolean leftSide = true;

	private static final long serialVersionUID = -6924799158120478860L;
	int time;
	public boolean lightNow = true;
	public float radius;

	public LightObject() {
		super();
		isDropped = true;
	}

	public LightObject(int objectId, int defId) {
		super(objectId,defId);
	}
	
	@Override
	public void applyDef(){
		ItemDef def = DefManager.allItems.get(getDefId());
		init(def);
	}
	
	public void init(ItemDef def) {
		if (!def.itemType.equalsIgnoreCase("light"))
			return;
		setImage(def.image);
		setDefId(def.id);
		radius = def.getIntProperty("lightRadius");

		onGround = def.getBoolProperty("lightonGround");
		setDefId(def.id);
		setItemCount(1);
//		if (item == null) {
//			item = new Item(World.getNextId(), def, null);
//			item.setCount(1);
//		}
		// проверяем, можно ли прицепить объект на стену слева или справа от
		// нынешних координат
		if (getTile() != null && !onGround && getType() == GROUND_TYPE) {
			if (getTile().getNeighbor(MapObject.LEFT) != null
					&& !getTile().getNeighbor(MapObject.LEFT).canMove()) {
				setType(LEFT_WALL_TYPE);
				setTile(getTile().getNeighbor(MapObject.LEFT));
				setLeft(false);
			} else if (getTile().getNeighbor(MapObject.RIGHT) != null
					&& !getTile().getNeighbor(MapObject.RIGHT).canMove()) {
				setType(RIGHT_WALL_TYPE);
				setTile(getTile().getNeighbor(MapObject.RIGHT));
				setLeft(true);
			} else {
				setType(GROUND_TYPE);
				setTile(getTile());
			}
			getTile().addListener(this);
		} else
			setType(GROUND_TYPE);
	}

	long lastClick;

	@Override
	public void onClick(int button, Player player) {
		if (distanceTo(player) < Config.tileSize * 2
				&& System.currentTimeMillis() - lastClick > 500) {
			lightNow = !lightNow;
			lastClick = System.currentTimeMillis();
			if (!isRemove())
				broadcastPacket(getInfo());
			// else if (button == Input.MOUSE_LEFT_BUTTON)
			// {
			// super.onClick(button, player);
			// }
			// */
		}
	}

	@Override
	public void onTouch(GameObject object) {}

	@Override
	public void objectChanged(GObject object) {}

	@Override
	public Packet getInfo() {
		if (info == null)
			info = new LightInfo();
		((LightInfo) info).x = getX();
		((LightInfo) info).y = getY();
		((LightInfo) info).id = getDefId();
		((LightInfo) info).oId = getObjectId();
		((LightInfo) info).radius = radius;
		((LightInfo) info).lights = (byte) (lightNow ? 1 : 0);
		return info;
	}

}
